package com.ytsky.hctechnologysys.controller;


import com.github.pagehelper.PageInfo;
import com.ytsky.hctechnologysys.entity.Stipend;
import com.ytsky.hctechnologysys.service.StipendService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Dell
 */
@Controller
public class StipendController {

    private  static final Logger logger = LoggerFactory.getLogger(StipendController.class);


    @Autowired
    private StipendService stipendService;

    /**
     *返回薪金信息添加界面
     * @return
     */
    @GetMapping("/stipend/moneyAdd")
    public ModelAndView moneyAddView(){
        ModelAndView mav = new ModelAndView("stipend/moneyAdd");
        return  mav;

    }


    /**
     * 返回薪金信息修改页面
     * @return
     */
    @GetMapping("/stipend/moneyChange")
    public ModelAndView moneyChangeView(
        @RequestParam(name = "pageNum",required = true,defaultValue = "1") int pageNum,
        @RequestParam(name = "pageSize",required = true,defaultValue = "100") int pageSize,
        @RequestParam(name = "keyword",required = false) String keyword
    ){
    ModelAndView mav = new ModelAndView("stipend/moneyChange");
            PageInfo<Stipend> page =  stipendService.findByKeyword(pageNum,pageSize,keyword);
            mav.addObject("page",page);
            return mav;
        }


    @GetMapping("/stipend/moneyModify")
    public ModelAndView stipendModifyView(
            @RequestParam(name = "id", required = true) int id,
            @RequestParam(name = "pageSize",required = true,defaultValue = "5") int pageSize,
            @RequestParam(name = "pageNum",required = true,defaultValue = "1") int pageNum,
            @RequestParam(name = "keyword", required = false) String keyword
    ){
        ModelAndView mav = new ModelAndView("stipend/moneyModify");
        // 调用服务方法根据ID查询编辑客户
        Stipend stipend = stipendService.findById(id);
        mav.addObject("stipend",stipend);
        return mav;
    }


    @GetMapping("/stipend/stipendRemove")
    public ModelAndView stipendRemove(
            @RequestParam(name = "id", required = true) int id,
            @RequestParam(name = "pageSize",required = true,defaultValue = "5") int pageSize,
            @RequestParam(name = "pageNum",required = true,defaultValue = "100") int pageNum,
            @RequestParam(name = "keyword", required = false) String keyword
    ) throws UnsupportedEncodingException {
        String redirectUrl = "redirect:/stipend/moneyChange?pageNum=" + pageNum +
                "&pageSize=" + pageSize +
                "&keyword=" + URLEncoder.encode(keyword,"utf-8");
        ModelAndView mav = new ModelAndView(redirectUrl);
        // 调用服务方法根据ID查询编辑客户
        boolean result = stipendService.remove(id);
        return mav;
    }





    @PostMapping("/stipend/moneyAdd")
    public ModelAndView moneyAdd(@Validated Stipend stipend, BindingResult bindingResult){
        //redirect表示重定向响应
        //给浏览器发送一个请求地址，而没有任何视图内容或数据
        //浏览器会使用收到的地址，重新发送一个Get请求，由于是新请求，因此没有缓存上一次请求的数据，从而达到防止重复提交表单的目的
        ModelAndView mav = new ModelAndView("redirect:/stipend/moneyAdd");

        Map<String,String> errorMessages = new HashMap<>();
        if (bindingResult.hasErrors()){
            //如果由验证错误消息，那么要进行处理
            //获得出现错误域，以及相应的错误消息文本
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            //错误信息放入到映射中
            for (FieldError error : fieldErrors){
                //从每一个域错误对象中取出域名称，错误消息，加到映射集合中
                errorMessages.put(error.getField(),error.getDefaultMessage());
            }
            //将错误信息发送给视图
            mav.addObject("errorMessages",errorMessages);
            //将客户填写的而信息，重新显示在表单中
            mav.addObject("stipend",stipend);
            //由于没有保存数据，因此不必进行重定向，内部转发请求到视图，同时还要保留请求数据，以及相应的信息
            mav.setViewName("/stipend/moneyAdd");
            System.out.println(stipend+"asda");
        }else{
            //如果没有错误信息，验证通过
            //调用服务方法保存客户数据
            boolean result = stipendService.append(stipend);
            if (result){
                logger.info("新增员工薪金信息成功 - "+stipend);
            }else{
                logger.info("新增员工薪金信息失败 - "+stipend);
            }
            System.out.println(stipend);
        }
        return  mav;
    }



    @PostMapping("/stipend/moneyModify")
    public ModelAndView stipendModify(
            Stipend stipend,
            @RequestParam(name = "pageNum", required = true,defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize", required = true,defaultValue = "5") int pageSize,
            @RequestParam(name = "keyword", required = false) String keyword
    ) throws UnsupportedEncodingException {
        String redirectUrl = "redirect:/stipend/moneyChange?pageNum="
                + pageNum + "&pageSize=" + pageSize +"&keyword="
                + URLEncoder.encode(keyword,"utf-8");
        ModelAndView mav = new ModelAndView(redirectUrl);
        boolean result = stipendService.modify(stipend);
        return mav;
    }

}
